package com.lzp.java.concurrent.threadcore.stopthread.wrongways;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 使用中断修复上一个案例
 * <p>
 *
 * @author lzp
 * @date 2020/02/01
 */
public class WrongWayVolatileCantStopFixed {

    public static void main(String[] args) throws InterruptedException {
        ArrayBlockingQueue storage = new ArrayBlockingQueue(10);

        WrongWayVolatileCantStopFixed outerClass = new WrongWayVolatileCantStopFixed();
        Producer producerTask = outerClass.new Producer(storage);
        Thread producer = new Thread(producerTask);
        producer.start();
        Thread.sleep(3000);

        Consumer consumer = outerClass.new Consumer(storage);
        while (consumer.needMoreNums()) {
            System.out.println(consumer.storage.take() + "被消费者消费");
            Thread.sleep(100);
        }
        System.out.println("消费者不再需要更多数据");

        // 停止生产者
        producer.interrupt();
    }

    class Producer implements Runnable {
        BlockingQueue storage;

        public Producer(BlockingQueue storage) {
            this.storage = storage;
        }

        @Override
        public void run() {
            // 生产100的倍数，到仓库
            int num = 1;
            try {
                while (num <= 5000 && !Thread.currentThread().isInterrupted()) {
                    if (num % 100 == 0) {
                        storage.put(num);
                        System.out.println("生产者生产" + num + "放入仓库");
                    }
                    num++;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println("生产者结束运行");
            }
        }
    }

    class Consumer {
        BlockingQueue storage;

        public Consumer(BlockingQueue storage) {
            this.storage = storage;
        }

        public boolean needMoreNums() {
            if (Math.random() > 0.95) {
                return false;
            }
            return true;
        }
    }

}

